package com.wyp168.juc.future;

import lombok.Getter;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName CompletableFutureExpMall
 * @Description TODO
 * @Author wyp168
 * @Date 2022/9/12 15:05
 */
public class CompletableFutureExpMall {
    private static List<NetMall> netMallList = Arrays.asList(
            new NetMall("jd"),
            new NetMall("tb"),
            new NetMall("tm")
    );

    public static List<String> getProduceNameAndPrice(List<NetMall> list, String produceName) {
        return list.stream().map(netMall -> String.format(produceName + "in %s price is %.2f", netMall.getNetMallName(), netMall.getProductPrice(produceName))).collect(Collectors.toList());
    }

    public static List<String> getProduceNameAndPriceByCompletableFuture(List<NetMall> list, String produceName) {
        return list.stream().map(netMall -> CompletableFuture.supplyAsync(() -> {
            return String.format(produceName + "in %s price is %.2f", netMall.getNetMallName(), netMall.getProductPrice(produceName));
        })).collect(Collectors.toList()).stream().map(s -> s.join()).collect(Collectors.toList());
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        //TODO
        CompletableFutureExpMall.getProduceNameAndPrice(netMallList, "mysql").forEach(System.out::println);
        long endTime = System.currentTimeMillis();
        System.out.println("costTime---" + (endTime - startTime) + "毫秒");
        System.out.println("-------------------------------------------------");
        long startTime1 = System.currentTimeMillis();
        //TODO
        CompletableFutureExpMall.getProduceNameAndPriceByCompletableFuture(netMallList, "mysql").forEach(System.out::println);
        long endTime1 = System.currentTimeMillis();
        System.out.println("costTime---" + (endTime1 - startTime1) + "毫秒");
    }


}

class NetMall {
    @Getter
    private String netMallName;

    public NetMall(String netMallName) {
        this.netMallName = netMallName;
    }

    public Double getProductPrice(String productName) {
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) {e.printStackTrace();}
        return ThreadLocalRandom.current().nextDouble(1) * 2 * (productName.charAt(0));
    }
}
